import { fetchSubProjects, addSubProject, deleteSubProject, updateProject, deleteProject, collectSubProject } from '../../../api/project';

Page({
  data: {
    projectId: null,
    projectName: '',
    subProjects: [],
    worktime: 0,
    overtime: 0,
    currentDate: '',
    showModal: false,
    newSubProjectName: '',
    editProjectName: ''
  },

  onLoad(options) {
    const { projectId, projectName } = options;
    this.setData({ projectId, projectName, editProjectName: projectName });
    const date = new Date().toISOString().slice(0, 7); 
    this.setData({ currentDate: date });
    this.fetchSubProjects(projectId);
    this.fetchWorkAndOvertime(projectId, date); // 获取日工和加班数据
  },

  onShow() {
    // 注册事件监听器
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel) {
      eventChannel.on('updateSubProjectName', (data) => {
        this.updateSubProjectName(data);
      });
    }
  },

  fetchSubProjects(id) {
    fetchSubProjects(id).then(response => {
      if (response.code === 1) {
        this.setData({
          subProjects: response.data
        });
      } else {
        console.error('Failed to fetch sub-projects');
      }
    }).catch(error => {
      console.error('Error fetching sub-projects:', error);
    });
  },

  fetchWorkAndOvertime(id, time) {
    console.log(id);
    console.log("111"+ time);
    collectSubProject(id, time).then(response => {
      if (response.code === 1) {
        const { worktime, overtime } = response.data;
        this.setData({
          worktime: worktime || 0,
          overtime: overtime || 0
        });
      } else {
        this.setData({
          worktime: 0,
          overtime: 0
        });
        console.error('Failed to fetch work and overtime data');
      }
    }).catch(error => {
      this.setData({
        worktime: 0,
        overtime: 0
      });
      console.error('Error fetching work and overtime data:', error);
    });
  },

  updateSubProjectName(updatedSubProject) {
    const { subProjects } = this.data;
    const index = subProjects.findIndex(item => item.id === updatedSubProject.id);
    if (index !== -1) {
      subProjects[index].name = updatedSubProject.name;
      this.setData({ subProjects });
    }
  },

  navigateToDetails(event) {
    const subProject = event.currentTarget.dataset.subproject;
    wx.navigateTo({
      url: `/pages/Project-management/subpdetial/subpdetial?subProjectId=${subProject.id}&subProjectName=${subProject.name}`
    });
  },

  showEditSubProjectModal(event) {
    const subProject = event.currentTarget.dataset.subproject;
    console.log(subProject);
    wx.navigateTo({
      url: `/pages/Project-management/editsubp/editsubp?subProjectId=${subProject.id}&subProjectName=${subProject.name}`,
      events: {
        updateSubProjectName: (data) => {
          this.updateSubProjectName(data);
        }
      }
    });
  },

  confirmDeleteSubProject(event) {
    const subProject = event.currentTarget.dataset.subproject;
    wx.showModal({
      title: '确认删除',
      content: `确定要删除小项目 "${subProject.name}" 吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deleteSubProject(subProject.id);
        }
      }
    });
  },

  deleteSubProject(id) {
    deleteSubProject(id).then(response => {
      if (response.code === 1) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        this.fetchSubProjects(this.data.projectId);
      } else {
        console.error('Failed to delete sub-project');
      }
    }).catch(error => {
      console.error('Error deleting sub-project:', error);
    });
  },

  viewVehicles() {
    const { projectId, projectName } = this.data;
    console.log(projectId+"145");
    wx.navigateTo({

      url: `/pages/Project-management/travel/travel?projectId=${projectId}&projectName=${projectName}`
    });
  },

  showEditProjectModal() {
    this.setData({
      showModal: true
    });
  },

  hideModal() {
    this.setData({
      showModal: false,
      newSubProjectName: ''
    });
  },

  onInputChange(event) {
    this.setData({
      editProjectName: event.detail.value
    });
  },

  onNewSubProjectInputChange(event) {
    this.setData({
      newSubProjectName: event.detail.value
    });
  },

  confirmEditProject() {
    const { projectId, editProjectName } = this.data;
    if (!editProjectName) {
      wx.showToast({
        title: '项目名称不能为空',
        icon: 'none'
      });
      return;
    }

    updateProject({ id: projectId, name: editProjectName }).then(response => {
      if (response.code === 1) {
        wx.showToast({
          title: '项目更新成功',
          icon: 'success'
        });
        this.setData({ projectName: editProjectName });
        const eventChannel = this.getOpenerEventChannel();
        if (eventChannel) {
          eventChannel.emit('updateProjectList'); // 通知上一页更新数据
        }
        this.hideModal();
        this.fetchSubProjects(projectId);
      } else {
        console.error('Failed to update project');
      }
    }).catch(error => {
      console.error('Error updating project:', error);
    });
  },

  addNewSubProject() {
    const { projectId, newSubProjectName } = this.data;
    if (!newSubProjectName) {
      wx.showToast({
        title: '小项目名称不能为空',
        icon: 'none'
      });
      return;
    }

    addSubProject({ projectId: projectId, name: newSubProjectName }).then(response => {
      if (response.code === 1) {
        wx.showToast({
          title: '小项目添加成功',
          icon: 'success'
        });
        this.setData({ newSubProjectName: '' });
        this.fetchSubProjects(projectId);
      } else {
        console.error('Failed to add sub-project');
      }
    }).catch(error => {
      console.error('Error adding sub-project:', error);
    });
  },

  confirmDeleteProject() {
    wx.showModal({
      title: '确认删除',
      content: `确定要删除大项目 "${this.data.projectName}" 吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deleteProject(this.data.projectId);
        }
      }
    });
  },

  deleteProject(id) {
    deleteProject(id).then(response => {
      if (response.code === 1) {
        wx.showToast({
          title: '大项目删除成功',
          icon: 'success'
        });
        const eventChannel = this.getOpenerEventChannel();
        if (eventChannel) {
          eventChannel.emit('updateProjectList'); // 通知上一页更新数据
        }
        wx.navigateBack(); // 返回上一页
      } else {
        console.error('Failed to delete project');
      }
    }).catch(error => {
      console.error('Error deleting project:', error);
    });
  },

  onDateChange(event) {
    const date = event.detail.value;
    this.setData({
      currentDate: date
    });
    this.fetchSubProjects(this.data.projectId);
    this.fetchWorkAndOvertime(this.data.projectId, date); // 获取新的日工和加班数据
  }
});
